import axios from 'axios'
import type {InternalAxiosRequestConfig, AxiosResponse, AxiosInstance} from 'axios'
import {message} from 'ant-design-vue'
import JSONBIG from 'json-bigint'
import router from '../router'


axios.defaults.transformResponse = [
    function (data){
        const jsonBig = JSONBIG({storeAsString: true})
        return jsonBig.parse(data)
    }
]
const axiosInstance: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_API_URL + import.meta.env.VITE_API_BASE_PATH,
    timeout: 600000,
})
// 添加请求拦截器
axiosInstance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 在发送请求之前做些什么
        const {method} = config
        config.headers['Authorization'] = sessionStorage.getItem('token')
        if (method === 'get') {
            config.params = config.params || {} // 检查并初始化 config.params
        } else {
            if (config.data instanceof FormData) {
                // config.data.append('brandCode', '')
            } else {
                config.data = config.data || {} // 检查并初始化 config.data
            }
        }
        return config
    },
    (error: any) => {
        // 处理请求错误
        return Promise.reject(error)
    }
)
// 添加响应拦截器
axiosInstance.interceptors.response.use(
    (response: AxiosResponse):any => {
        const {code, message: msg} = response.data
        if (code === '4104' || code === '4103'){
            //无权限
            message.error({content: msg || '请求错误'})
            return false
        }
        if (code === '4101' || code === '4102' || code === '4105') {
            // token失效
            message.error({
                content: msg || '请求错误',
                onClose: () => {
                },
            })
        }
        if (code !== '2000' && response.request.responseType !== 'blob') {
            message.error({content: msg || '请求错误'})
        }
        // 对响应数据做点什么
        return response
    },
    (error: any) => {
        // 处理响应错误
        return Promise.reject(error)
    }
)
export default axiosInstance
